package com.jerry.security.security;

import com.jerry.security.model.Role;
import com.jerry.security.model.User;
import com.jerry.security.service.RoleService;
import com.jerry.security.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Jerry.Wu
 * @description:
 * @date 2018/8/29 19:12
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Resource
    private UserService mUserService;

    @Resource
    private RoleService mRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = mUserService.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        // 通过直接查的方式，不用懒加载，这里hibernate的session事务还没启动，
        // 如果使用懒加载获取，在获取时查询的session已经被关闭，会报no session的错
        List<Role> roles = mRoleService.findRolesByUserId(user.getId());
        user.setRoles(roles);
        MyUserDetails myUserDetails = new MyUserDetails(user.getId(), user.getUsername(), user.getPassword(), user.getNickname(), user.getEnabled(), roles);
        return myUserDetails;
    }


}
